/**
 * 
 */
package core;

/**
 * @author Boaz
 *
 */
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import db.IQuestionsDb;


public class QuestionPool {
	private static final int NUM_OF_WRONG_ANSWERS = 3;
	private final List<QuestionPattern> _questionPatternsArray;
	private final Random _random;

	//	CTOR
	public QuestionPool(Random random) {
		_random = random;
		_questionPatternsArray = new ArrayList<QuestionPattern>();

		//	use reflection to initialize fields of type QuestionPatterns
		for (Field field : this.getClass().getDeclaredFields()) {

			if (!field.getType().equals(QuestionPattern.class)) {
				continue;
			}

			try {
				QuestionPattern questionPattern = (QuestionPattern) field.get(this);
				_questionPatternsArray.add(questionPattern);
			} catch (Exception e) {
				Log.warning("Error adding " + field.getName() + "to questions list");
			}
		}
		if (_questionPatternsArray.size() == 0) {
			throw new RuntimeException("No question patterns found");
		}
		
		Log.info("Created " + _questionPatternsArray.size() + " Question Patterns ");
	}

	public synchronized Question getNewQuestion(IQuestionsDb db) throws FailedGeneratingQuestionException {
		int randomPatternNumber = _random.nextInt(_questionPatternsArray.size());	//	draw a random question pattern
		try {
			QuestionPattern randomQuestionPattern = _questionPatternsArray.get(randomPatternNumber);
			Log.info("Generating question pattern #" + randomQuestionPattern + ": " + randomQuestionPattern.getPattern());
			Question question = randomQuestionPattern.generateNewQuestion(db, _random);
			return question;
		} catch (Exception e) {
			Log.severe("Failed generating question");
			throw new FailedGeneratingQuestionException("Failed to generate question", e);
		}
	}
}